'use strict'

const Service = require('egg').Service

class FriendService extends Service {
  /**
   * 申请添加好友
   * @param {*} param0 
   */
  async createFriendApply({ s_user, r_user, remark }) {
    const values = {
      s_user,
      r_user,
      remark,
      is_read: 0,
      create_time: new Date()
    }
    await this.app.mysql.insert('t_friend_apply', values);
    return values;
  }

  /**
   * 处理好友申请
   * @param {*} param0 
   */
  async dealFriendApply({ id, status }) {
    const sql = `
      update
        t_friend_apply t
      set
        status = ${status}, is_read = 1
      where
        t.id = ${id}
    `;
    return await this.app.mysql.query(sql);
  }

  /**
   * 创建好友关系
   * @param {*} param0 
   */
  async createFriend({ uid, eid }) {
    const sql = `
      insert into
      t_friend (uid, eid)
      values(${uid}, ${eid})
    `;
    const row = await this.app.mysql.query(sql);
    return JSON.parse(JSON.stringify(row));
  }

  /**
   * 获取好友申请详情
   * @param {*} param0 
   */
  async getFriendApplyDetail({ id }) {
    const sql = `
      select
        *
      from
        t_friend_apply t
      where
        t.id = ${id}
    `;
    const list = await this.app.mysql.query(sql);
    return JSON.parse(JSON.stringify(list[0]));
  }
  
  /**
   * 获取好友申请通知列表
   * @param {*} param0 
   */
  async getNewFirentNotice({ user_id }) {
    const sql = `
      select
        t.*,
        t_user.nickname,
        t_user.avatar
      from
        t_friend_apply t
      left join
        t_user
      on
        t.s_user = t_user.id
      where
        t.r_user = ${user_id}
      `;
    return await this.app.mysql.query(sql);
  }

  /**
   * 获取好友列表
   * @param {*} param0 
   */
  async getFriendList({ user_id }) {
    const sql = `
      select
        *
      from
        t_friend t
      left join
        t_user
      on
        t_user.id = (
          case when t.uid = ${user_id} then t.eid else t.uid end
        )
      where
        (t.uid = ${user_id}) or (t.eid = ${user_id})
    `;
    return await this.app.mysql.query(sql);
  }
}

module.exports = FriendService;
